package org.pku_uestc.hackathon;

import java.io.IOException;

import org.pku_uestc.hackathon.sensor.mobile.CallReceiver;
import org.pku_uestc.hackathon.sensor.mobile.SmsReceiver;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ToggleButton;

public class SilentActivity extends Activity implements
		OnCheckedChangeListener, OnClickListener, AnimationListener {

	private Animation translateDown;
	private Animation alphaIn, alphaOut;
	private ToggleButton smsTb;
	private ToggleButton phoneTb;
	private Button lightBtn;
	private Button contactBtn;
	private ImageView arrow;
	private AudioManager mAudioManager;
	private Vibrator vibrator;
	private MediaPlayer mNotificationPlayer;
	private MediaPlayer mRingtonePlayer;
	private Uri ringtoneUri, notificationUri;
	private CallReceiver mCallReceiver;
	private SmsReceiver mSmsReceiver;
	private int mode;
	private boolean isAnimationFinish = true;
	private boolean hasVibrate;
	private boolean isRegister = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.silent);
		smsTb = (ToggleButton) findViewById(R.id.silent_sms);
		phoneTb = (ToggleButton) findViewById(R.id.silent_phone);
		lightBtn = (Button) findViewById(R.id.silent_light);
		contactBtn = (Button) findViewById(R.id.silent_contact);
		arrow = (ImageView) findViewById(R.id.silent_arrow);
		translateDown = AnimationUtils.loadAnimation(this, R.anim.arrow_translate);
		alphaIn = AnimationUtils.loadAnimation(this, R.anim.arrow_alpha_in);
		alphaOut = AnimationUtils.loadAnimation(this, R.anim.arrow_alpha_out);
		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
		notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		mode = getMode();
		Log.i("HHH", "mode = "+mode);
		if (mode > 0) {
			hasVibrate = true;
		}
		translateDown.setAnimationListener(this);
		alphaIn.setAnimationListener(this);
		alphaOut.setAnimationListener(this);
		smsTb.setOnCheckedChangeListener(this);
		phoneTb.setOnCheckedChangeListener(this);
		lightBtn.setOnClickListener(this);
		contactBtn.setOnClickListener(this);
		arrow.setVisibility(View.GONE);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		if(mRingtonePlayer != null && mRingtonePlayer.isPlaying()) {
			mRingtonePlayer.stop();
		}
		if(mNotificationPlayer != null && mNotificationPlayer.isPlaying()) {
			mNotificationPlayer.stop();
		}
		if(mCallReceiver != null) {
			unregisterReceiver(mCallReceiver);
		}
		if(mSmsReceiver != null) {
			unregisterReceiver(mSmsReceiver);
		}
		Log.i("HHH", "onDestroy mode = "+mode);
		mAudioManager.setRingerMode(mode);
		isRegister = false;
	}

	private void startAnimation() {
		isAnimationFinish = false;
		arrow.setVisibility(View.VISIBLE);
		arrow.startAnimation(alphaIn);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.silent_phone:
			break;
		case R.id.silent_sms:
			break;
		case R.id.silent_contact:
			Intent i = new Intent(this, ContactsActivity.class);
			startActivityForResult(i, 0);
			break;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.i("HHH", "requestCode:"+requestCode);
		Log.i("HHH", "intent:"+data);
		if (requestCode == 0) {
			String[] phones = data.getExtras().getStringArray("phone");
			registerBroadcast(phones);
		}
	}

	private void registerBroadcast(String[] phones) {
		Log.i("HHH", "register "+isRegister);
		if (!isRegister) {
			mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
			WhiteListInterface whitelist = new WhiteListInterface() {
				
				@Override
				public void onPass(int type) {
					Log.i("hhh", "type="+type);
					if (type == WhiteListInterface.TYPE_CALL) {
						playRingtone(getApplicationContext());
					} else if (type == WhiteListInterface.TYPE_SMS){
						playNotification(getApplicationContext());
					}
				}
			};
			if (phoneTb.isChecked()) {
				IntentFilter callFilter = new IntentFilter();
				callFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
				callFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
				mCallReceiver = new CallReceiver();
				mCallReceiver.setPhones(phones, whitelist);
				registerReceiver(mCallReceiver, callFilter);
			}
			if (smsTb.isChecked()) {
				IntentFilter smsFilter = new IntentFilter();
				smsFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
				smsFilter.addAction(SmsReceiver.SMS_RECEIVED);
				mSmsReceiver = new SmsReceiver();
				mSmsReceiver.setPhones(phones, whitelist);
				registerReceiver(mSmsReceiver, smsFilter);
			}
			isRegister = true;
		}
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		if (animation.equals(alphaIn)) {
			arrow.startAnimation(translateDown);
		} else if (animation.equals(translateDown)) {
			arrow.startAnimation(alphaOut);
		} else if (animation.equals(alphaOut)) {
			arrow.setVisibility(View.GONE);
			isAnimationFinish = true;
		}
	}

	@Override
	public void onAnimationRepeat(Animation animation) {

	}

	@Override
	public void onAnimationStart(Animation animation) {

	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			if (isAnimationFinish) {
				startAnimation();
			}
			mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
		}
	}

	private int getMode() {
		return mAudioManager.getRingerMode();
	}

	private void playRingtone(Context context) {
		mRingtonePlayer = new MediaPlayer();
		mRingtonePlayer.reset();
		try {
			mRingtonePlayer.setDataSource(context, ringtoneUri);
			mRingtonePlayer.prepare();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mRingtonePlayer.start();
	}

	private void playNotification(Context context) {
		Log.i("hhh", "noti");
		mNotificationPlayer = new MediaPlayer();
		mNotificationPlayer.reset();
		try {
			mNotificationPlayer.setDataSource(context, notificationUri);
			mNotificationPlayer.prepare();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (hasVibrate)
			vibrate();
		mNotificationPlayer.start();
	}

	private void vibrate() {
		long[] pattern = { 100, 400, 100, 400 };
		vibrator.vibrate(pattern, 2);
	}
	
	public interface WhiteListInterface {
		public static int TYPE_CALL = 1;
		public static int TYPE_SMS = 2;
		void onPass(int type);
	}

}
